package src

import (
	"fmt"
	"net/http"
	"utils"
	"html/template"
	"appengine"
	"appengine/memcache"
	"github.com/russross/blackfriday"
)

func init() {
	http.HandleFunc("/info/", readmeHandler)
}

func readmeHandler(w http.ResponseWriter, r *http.Request) {
	c := appengine.NewContext(r)
	w.Header().Set("Content-Type", "text/html; charset=utf-8")
	
	//uri := r.URL.RequestURI();
	//urlPath := r.URL.Path[len("/shouthello/"):]
	
	name := r.URL.Path[len("/info/"):]
	
//	pId := r.FormValue("id") 
//	id,_ := strconv.ParseInt(pId, 10, 0)
	readme, err := utils.GetReadme(name, r)
	
	if err != nil {
		fmt.Fprintln(w, "Error")
		return
	}
	
	//Add to recent
	var recent = [] utils.Readme {}
  	memcache.Gob.Get(c, "recent", &recent)
  	
  	var check = 0
    for i := 0 ; i < len(recent); i++ {
		if (recent[i].Name == readme.Name) {
			check = 1
		}
	}

    if check != 1 {
	    if len(recent) <=19 {
			recent = append(recent, readme)
		} else {
			for i:= 0 ; i<len(recent)-1 ; i++ {
				recent[i] = recent[i+1]
			}
			recent = recent[:len(recent)-1]
			
			recent = append(recent, readme)
		}
		
		item1 := &memcache.Item {
		   Key: "recent",
		   Object: recent, 
		} 
		
		memcache.Gob.Set(c, item1)
    }
  	
  	funcMap := template.FuncMap{
    		"markdown": blackfriday.MarkdownCommon,
   	}
  	
	//Display template
	t := template.Must(template.New("Readme").Funcs(funcMap).ParseFiles("templates/pages/readme.html", "templates/layouts/header.html", "templates/layouts/footer.html"))
	
	t.Execute(w, map[string]interface{}{"readme" : readme, "recent" : recent, "content" : template.HTML(blackfriday.MarkdownCommon([]byte(readme.Content)))})

//	output := template.HTML(blackfriday.MarkdownCommon([]byte(readme.Content)))
//	fmt.Fprintln(w, output)
}